package videoplay

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
)

// SavePlaySequel 保存播放续集数据
func (p *sVideoPlay) SavePlaySequel(ctx context.Context, en entity.VideoPlaySequel) error {
	// 获取播放续集ID
	var item model.VideoPlaySequelBasicItem
	_ = p.SequelModel().Scan(ctx, g.Map{
		dao.VideoPlaySequel.Columns().PlayId:        en.PlayId,
		dao.VideoPlaySequel.Columns().VideoSequelId: en.VideoSequelId,
	}, &item)

	// 保存播放记录
	en.Id = item.Id
	_, err := dao.VideoPlaySequel.Ctx(ctx).OmitEmpty().Save(en)
	if err != nil {
		return exception.New(`保存播放续集记录失败`)
	}
	return nil
}

// GetPlayResultsMapByPlayId 通过播放ID获取用户播放视频结果集
func (p *sVideoPlay) GetPlayResultsMapByPlayId(ctx context.Context, playId uint) (res map[uint]*model.VideoPlaySequelResultItem, err error) {
	res = make(map[uint]*model.VideoPlaySequelResultItem)
	var (
		list []model.VideoPlaySequelResultItem
	)
	err = p.SequelModel().Scan(ctx, g.Map{
		dao.VideoPlaySequel.Columns().PlayId: playId,
	}, &list)
	if err != nil {
		return nil, exception.New(`暂无播放结果集`)
	}

	// 迭代出来结果集
	for _, item := range list {
		res[item.VideoSequelId] = &item
	}
	return
}

// MustPlayResultsMap 通过播放ID获取用户播放结果集
func (p *sVideoPlay) MustPlayResultsMap(ctx context.Context, playId uint) map[uint]bool {
	results, err := p.GetPlayResultsMapByPlayId(ctx, playId)
	if err != nil {
		return nil
	}
	resultsMap := make(map[uint]bool)
	for key, _ := range results {
		resultsMap[key] = true
	}
	return resultsMap
}
